const { DataTypes } = require("sequelize");
const sequelize = require("../config/sequelize");
const Goods = require("../models/goods");
const User = require("../models/user");

const GoodsConversion = sequelize.define(
  "GoodsConversion",
  {
    score:{
        type:DataTypes.INTEGER,
        allowNull:false,
        comment:'商品兑换所用积分'
    },
    useState:{
        type:DataTypes.INTEGER,
        allowNull:false,
        defaultValue:1,
        comment:'商品使用状态' //（1代表未使用，2代表已使用，0代表已过期）
    },
    useDate:{
        type:DataTypes.STRING,
        comment:'兑换商品使用时间'
    },
    endDate:{
        type:DataTypes.STRING,
        allowNull:false,
        comment:'兑换商品使用到期时间'
    }
  },
  {
    sequelize:sequelize,
    tableName:'goods_conversion',
    paranoid:true,
    underscored:true
  }
);

GoodsConversion.belongsTo(User,{
    constraints:false,
    foreignKey:'userId',
    as:'user'
});

GoodsConversion.belongsTo(Goods,{
    constraints:false,
    foreignKey:'goodsId',
    as:'goods'
});

GoodsConversion.afterCreate(async (goodsConversion) => {
    // 商品兑换数+1
    await Goods.increment({num: 1}, {where: {id: goodsConversion.goodsId}});
});

module.exports = GoodsConversion;
